package cz.ctu.guiproject.client.resources.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.Context;
import android.util.Log;
import cz.ctu.guiproject.client.resources.ContextProvider;
import static cz.ctu.guiproject.client.resources.constants.Logger.*;

/**
 * Provides static methods for saving and loading text files into Android
 * internal storage.
 * 
 * @author tomas.buk
 * 
 */
public class FileHandler {

	private static final Context context;
	static {
		context = ContextProvider.getInstance().getContext();
	}

	/**
	 * Loads text file with given filename from Android internal storage
	 * 
	 * @param filename
	 * @return
	 */
	// TODO chyba jako prase, filenotfoundexception precen neni takhle nikdy
	// vyhozena, ale pohlcena uvnitr catch bloku(mozna)
	public static String loadTextFile(String filename) throws FileNotFoundException {
		final StringBuilder sb = new StringBuilder();
		// get file
		try {
			final FileInputStream fis = context.openFileInput(filename);
			final BufferedReader br = new BufferedReader(new InputStreamReader(fis));

			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			fis.close();

		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
			return null;
		}

		return sb.toString();
	}

	/**
	 * Save text file with given name and content into Android internal storage
	 * 
	 * @param filename
	 * @param data
	 */
	public static void saveTextFile(String filename, String data) {

		try {
			final FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);

			fos.write(data.getBytes());
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e) {
			Log.e(TAG, e.getMessage());
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		}
	}
}